<!--
*@Author: zt
*@Description: 部门管理
*@Date: 2024-08-14
-->
<template>
  <a-layout class="f-h-100">
    <u-collapsed-sider class="f-padding-6">
      <a-layout>
        <a-layout-header
          style="
            height: auto;
            padding: 0;
            line-height: unset;
            background-color: #fff;
          "
          v-if="userInfo['whoAmI'] == 1"
        >
          <a-row class="f-w-100">
            <a-col flex="1" class="f-padding-r20 f-padding-l6">
              <u-cascader
                v-model:value="fkunitsid"
                :options="unitTreeData"
                change-on-select
                :field-names="{
                  label: 'name',
                  value: 'keyid',
                  children: 'children',
                }"
                @change="getTree('unit')"
              />
            </a-col>
          </a-row>
        </a-layout-header>
      </a-layout>
      <u-tree
        :treeData="treeData"
        ref="treeRef"
        :showSearch="false"
        :fieldNames="{ title: 'name', key: 'keyid', children: 'children' }"
        v-model:expandedKeys="treeExpandes"
        @select="deptTreeClick"
      />
    </u-collapsed-sider>
    <a-layout-content
      class="s-bg-white"
      style="margin-left: 12px; padding: 12px"
    >
      <a-layout class="f-h-100">
        <a-layout-header
          class="f-h-auto"
          style="padding: 0 0 12px; line-height: unset; background: #fff"
        >
          <a-space>
            <u-icon-button itype="add" @click="addBtn">新增子级</u-icon-button>
            <u-icon-button
              itype="save"
              @click="submit"
              :disabled="form['keyid'] == -1"
            >
              保存
            </u-icon-button>
            <u-icon-button
              itype="delete"
              @click="deleteBtn"
              :disabled="form['keyid'] == -1"
            >
              删除
            </u-icon-button>
          </a-space>
        </a-layout-header>
        <a-layout-content class="s-bg-white" style="padding: 0">
          <u-form
            :elements="elements"
            :model="form"
            ref="formRef"
            v-bind="$attrs"
          />
        </a-layout-content>
      </a-layout>
    </a-layout-content>
  </a-layout>
</template>
<script lang="ts" setup>
import { isSel } from '@/common/model/base';
import { createNamespacedHelpers } from 'vuex';
import { disableTreeKeyid } from '@/util/format.ts'
import { alertC, nullC, isValue } from '@/util/common';
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useLoginStore, useBaseStore } from '@/store';
import enmuService from '@/service/common/enmu.service';
import * as deptService from '@/service/system/dept/index';
import * as unitService from '@/service/system/unit/index';

const { userInfo } = storeToRefs(useLoginStore());
const { DEPT_TYPE } = storeToRefs(useBaseStore());
const fkunitsid = ref<string[]>([userInfo.value['unitId']]);
const unitTreeData = ref([]);
let treeCurrentData = reactive<any>({});
const treeData = ref([]);
const treeExpandes = ref([]);

const form = reactive<any>({
  isuse: '1',
  keyid: '',
  fkunitsid: '',
  fkparentid: '',
  name: '',
  code: '',
  depttype: '',
  remark: '',
});

let elements = reactive([
  {
    element: 'treeselect',
    label: '父级',
    col: { span: 24 },
    key: 'fkparentid',
    formItemProps: { labelWidth: '90px' },
    componentProps: {
      treeData: computed(() => treeData.value),
      fieldNames: { label: 'name', value: 'keyid' },
    },
  },
  {
    element: 'input',
    label: '部门名称',
    col: { span: 24 },
    key: 'name',
    data: [],
    formItemProps: { labelWidth: '90px' },
    componentProps: { required: true, maxlength: 50, showCount: true },
  },
  {
    element: 'number',
    label: '部门代码',
    col: { span: 24 },
    key: 'code',
    data: [],
    formItemProps: { labelWidth: '90px' },
    componentProps: { required: true, percision: true },
  },
  {
    element: 'select',
    label: '部门类型',
    col: { span: 24 },
    key: 'depttype',
    formItemProps: { labelWidth: '90px' },
    componentProps: {
      required: true,
      options: computed(() => DEPT_TYPE.value),
      fieldNames: { label: 'name', value: 'id' },
    },
  },
  {
    element: 'textarea',
    label: '备注',
    col: { span: 24 },
    key: 'remark',
    data: [],
    formItemProps: { labelWidth: '90px' },
    componentProps: { maxlength: 200, showCount: true },
  },
  {
    element: 'select',
    label: '是否使用',
    col: { span: 24 },
    key: 'isuse',
    data: [],
    formItemProps: { labelWidth: '90px' },
    componentProps: { required: true, options: isSel() },
  },
]);

onMounted(() => {
  getEnum();
  getUnitTree();
  getTree('init');
});
// 获取部门类型下拉数据
const getEnum = () => {
  let index = elements.findIndex(item => item.key == 'depttype');
  if (index != -1) {
    elements.splice(index, 1, { ...elements[index], data: DEPT_TYPE.value });
  }
};

const formRef = ref();
// 获取部门树形数据
// type = init 为初次进入时的加载
const getTree = (type?: string) => {
  if (type == 'unit') {
    formRef.value.form.resetFields();
    treeCurrentData = {};
  }

  let tFkunitsid = fkunitsid.value.length == 0 ? userInfo.value['unitId'] : fkunitsid.value[fkunitsid.value.length - 1]

  return deptService
    .tree(tFkunitsid)
    .then(res => {
      if (res.code == 0) {
        treeData.value = res.data;

        elements.splice(0, 1, { ...elements[0], data: treeData.value });
        if (treeData.value.length != 0 && type == 'init') {
          treeExpandes.value.splice(
            0,
            treeExpandes.value.length,
            nullC(treeData.value[0]['keyid'])
          );
        }
      }
    })
    .catch(() => {});
};

// 获取树形
const getUnitTree = () => {
  unitService
    .tree('')
    .then(res => {
      if (res.code == 0) {
        unitTreeData.value = res.data;
      }
    })
    .catch(() => {});
};

//部门树形选择
const deptTreeClick = (keys, { node }) => {
  formRef.value.form.resetFields();
  treeCurrentData = node.dataRef;
  form.keyid = treeCurrentData.keyid;

  deptService
    .singleQuery(treeCurrentData.keyid)
    .then(res => {
      if (res.code == 0) {
        if (res.data) {
          for (let key in form) {
            if (isValue(res.data[key])) {
              form[key] = nullC(res.data[key]);
            }
          }
          form.fkparentid = treeCurrentData.fkparentid;
          form.isuse = nullC(form.isuse) + '';
          form.depttype = nullC(form.depttype) + '';
        } else {
          formRef.value.form.resetFields();
        }

        elements.splice(0, 1, {
          ...elements[0],
          data: disableTreeKeyid(treeData, keys['keyid']),
        });

        setTimeout(() => clearValidate(), 100);
      }
    })
    .catch(() => {});
};

const treeRef = ref();
// 保存
const submit = () => {
  if (form['keyid'] == -1) {
    alertC('顶级节点不能修改!');
    return;
  }

  if (!treeCurrentData['keyid']) {
    alertC('请先在左侧选择节点!');
    return;
  }

  formRef.value.form.validate().then(vali => {
    if (!vali) {
      alertC('请先将必填字段填写完毕!');
      return;
    }

    const url = form.keyid ? 'update' : 'add';
    clearValidate();
    getTree();
    form.fkunitsid = form.fkunitsid[form.fkunitsid.length - 1];
    deptService[url](form)
      .then(async res => {
        if (res.code == 0) {
          alertC(res.msg, 'success');
          if (res.data) {
            for (let key in form) {
              if (isValue(res.data[key])) {
                form[key] = res.data[key];
                // this.$set(this.form, key, nullC(res.data.data[key]))
              }
            }
            treeCurrentData = res.data;
          }
          form.isuse += '';
          form.depttype += '';

          await getTree();
          treeExpandes.value.splice(
            0,
            treeExpandes.value.length,
            form.fkparentid == 0 ? '1' : form.fkparentid
          );
          nextTick(() => {
            // treeRef.value.tree.value.setCurrentKey(form.keyid);
          });
        } else {
          alertC(res.msg, 'warning');
        }
      })
      .catch(() => {});
  });
};

// 新增子级
const addBtn = () => {
  if (!isValue(fkunitsid.value)) {
    alertC('请先选择单位!');
    return;
  }

  if (!isValue(treeCurrentData['keyid'])) {
    alertC('请先在左侧选择节点!');
    return;
  }

  clearValidate();
  getTree();
  formRef.value.form.resetFields();
  form.fkunitsid = fkunitsid.value;

  form['fkparentid'] = treeCurrentData['keyid'];

  form['isuse'] = '1';
  // this.$set(this.form, 'fkparentid', this.treeCurrentData['keyid'])
  // this.$set(this.form, 'isuse', '1')
  form.keyid = '';
  setTimeout(() => clearValidate());
};

// 删除
const deleteBtn = () => {
  if (!isValue(treeCurrentData['keyid'])) {
    alertC('请选择要删除的节点!');
    return;
  }

  if (treeCurrentData['keyid'] == -1) {
    alertC('不能删除顶级节点!');
    return;
  }

  clearValidate();
  getTree();
  deptService
    .del({ ids: treeCurrentData['keyid'] })
    .then(res => {
      if (res.code == 0) {
        alertC(res.msg, 'success');
        getTree();
        formRef.value.form.resetFields();
        form.keyid = '';
        treeCurrentData = {};
        form.keyid = '';
        form.fkparentid = '';
      } else {
        alertC(res.msg, 'warning');
      }
    })
    .catch(err => {});
  // 确认删除
  // confirmC({
  //   msg: "确认删除选中节点？",
  //   title: "删除数据",
  // })
  //   .then(() => {

  //   })
  //   .catch((err) => {});
};

// 清除已有的表单验证结果
const clearValidate = () => {
  formRef.value.form.clearValidate();
};

watch(
  () => form.keyid,
  nval => {
    if (isValue(nval)) {
      let index = elements.findIndex(item => item.key == 'fkparentid');
      if (index != -1) {
        elements.splice(index, 1, {
          ...elements[index],
          // disabled: nval && nval != "-1" ? false : true,
        });
      }
    }
  }
);
</script>
<style lang="scss"></style>
